var dtree;
var $;
var table;
var layer;
var form;
var upload;
layui.extend({
    dtree:'../layui/layui_ext/dtree/dtree'
}).use(['dtree','table','element','layer','upload'],function(){
    dtree=layui.dtree;
    $=layui.jquery;
    table=layui.table;
    layer=layui.layer;
    form=layui.form;
    upload=layui.upload;




    /*高级检索开始*/
    $("#btn2_id").on("click",function(){
        layer.open({
            type:2,
            title:"高级检索",
            area:['450px','300px'],
            shade:0.4,
            offset:'auto',
            content:"AdvancedRetrieval.html",

        })
        window.layer_2=layer;
        var tab=localStorage.getItem("tab");
        if(tab!=null){
            TabView(tab);
        }
    });

    //课程分类下拉菜单
    $.ajax({
        url: "/SyOperationController/selCourseClassSelect",
        type: "get",
        dataType: "json",
        success: function (data) {
            for(var a=0;a<data.data.length;a++){
                $("#city").append("<option value='"+data.data[a].id+"'>"+data.data[a].name+"</option>");
            }
            form.render();
        }
    });

    seTab1=function(){
        var beizhu=$("#beizhu").val();
        var status=$("#status").val();
        var cstatus=$("#cstatus").val();
        var num=$("#num").val();
        $.ajax({
            url:"/SyteacherSelController/SeCurriculumTab",
            type:"post",
            dataType:"json",
            data:{"classid":'',"courseName":'',"coursenprice":'',"intro":beizhu,"status":status,"cstatus":cstatus,"num":num},
            success:function(data){
                TabView(data.data);
            }
        })
    }



    //页面刷新
    $("#btn_1").on('click',function(){
        location.reload(true);
    })
    //ztree
    setDtree();
    function setDtree(){
        $.ajax({
            url:"/SyteacherSelController/seCurriculumTree",
            type:"post",
            dataType:"json",
            data:[],
            success:function(data){
                DtreeView(data.data);
            }
        })
    }
    function DtreeView(data){


        $(function(){
            //点击节点获取值
            function zTreeOnClick(event, treeId, treeNode) {
                seTab(treeNode.id,'','','','','','','');
                return false;
            };
            var ZtreeTile;
            function OnRightClick(event, treeId, treeNode) {
                if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
                    zTree.cancelSelectedNode();
                    showRMenu("root", event.clientX, event.clientY);
                } else if (treeNode && !treeNode.noR) {
                    ZtreeTile=treeNode;
                    showRMenu("node", event.clientX, event.clientY);
                }
            }

            function showRMenu(type, x, y) {
                $("#rMenu ul").show();
                if (type=="root") {
                    $("#m_del").hide();
                    $("#m_check").hide();
                    $("#m_unCheck").hide();
                } else {
                    $("#m_del").show();
                    $("#m_check").show();
                    $("#m_unCheck").show();
                }

                y += document.body.scrollTop;
                x += document.body.scrollLeft;
                rMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});

                $("body").bind("mousedown", onBodyMouseDown);
            }
            function hideRMenu() {
                if (rMenu) rMenu.css({"visibility": "hidden"});
                $("body").unbind("mousedown", onBodyMouseDown);
            }
            function onBodyMouseDown(event){
                if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length>0)) {
                    rMenu.css({"visibility" : "hidden"});
                }
            }
            //添加节点
            $("#m_add").on("click",function() {
                hideRMenu();
                //绑定添加事件，并定义添加操作
                var parentId=ZtreeTile.id;
                layer.open({
                    type:1,
                    title:"添加节点",
                    area:['400px','200px'],
                    shade:0.4,
                    offset:'auto',
                    content:"<div class='layui-inline' style='margin:40px 0px 0px 40px;z-index: 10'>" +
                        "<label class='layui-form-label'>分类名称：</label>" +
                        "<div class='layui-input-block'>" +
                        "<input type='text' name='name' id='treeNode_id' class='layui-input' placeholder='课程分类'/>" +
                        "</div>" +
                        "</div>",
                    btn:['添加','取消'],
                    yes:function(){
                        var name=$("#treeNode_id").val();
                        $.ajax({
                            url:"/SyteacherSelController/AddCurriculumTree",
                            type:"post",
                            dataType:"json",
                            data:{"parentId":parentId,"name":name},
                            success:function(dat){
                                location.reload(true);
                            }
                        })

                    }
                })
            });
            //修改节点
            $("#m_check").on("click",function(){
                layer.open({
                    type:1,
                    title:"修改节点",
                    area:['400px','200px'],
                    shade:0.4,
                    offset:'auto',
                    content:"<div class='layui-inline' style='margin:40px 0px 0px 40px;z-index: 10'>" +
                        "<label class='layui-form-label'>分类名称：</label>" +
                        "<div class='layui-input-block'>" +
                        "<input type='text' name='name' id='treeNode_id' class='layui-input' placeholder='课程分类'/>" +
                        "</div>" +
                        "</div>",
                    btn:['修改','取消'],
                    yes:function(){
                        var name=$("#treeNode_id").val();
                        var id = ZtreeTile.id
                        $.ajax({
                            url:"/SyteacherSelController/UpCurriculumTree",
                            type:"post",
                            dataType:"json",
                            data:{"id":id,"Newname":name},
                            success:function(data){
                                location.reload(true);
                            }
                        });
                    }

                });
                hideRMenu();
            });
            //删除
            $("#m_del").on("click",function() {
                $.ajax({
                    url:"/SyteacherSelController/deCurriculumTree",
                    type:"post",
                    dataType:"json",
                    data:{"id":ZtreeTile.id},
                    success:function(data){
                        location.reload(true);
                    }
                });
            });
            function resetTree() {
                hideRMenu();
                $.fn.zTree.init($("#treeDemo"), setting, zTreeNodes);
            }

            var zTree, rMenu;
            $(document).ready(function(){
                $.fn.zTree.init($("#treeDemo"), setting, zTreeNodes);
                zTree = $.fn.zTree.getZTreeObj("treeDemo");
                rMenu = $("#rMenu");
            });


            var setting={
                callback: {
                    onRightClick: OnRightClick,
                    onClick: zTreeOnClick,
                },
                view: {
                    dblClickExpand: false,
                    showIcon: false,

                },
            };


            var zTreeNodes=data;
            var city = $.fn.zTree.init($("#tree"), setting, zTreeNodes);
        });


    }











    seTab('','','','','','','');

    /*查询表结构开始*/
    function seTab(id,name,price,intro,status,cstatus,num){
        //获取登录信息
        var user=localStorage.getItem("user");
        user=JSON.parse(user);//将获取json字符串转json对象

        $.ajax({
            url:"/SyteacherSelController/SeCurriculumTab",
            type:"post",
            dataType:"json",
            data:{"classid":id,"courseName":name,"coursenprice":price,"intro":intro,"status":status,"cstatus":cstatus,"num":num,"userId":user.user_id},
            success:function(data){
                TabView(data.data);
            }
        })
    }
    /*查询表结构结束*/

    /*渲染表开始*/
    function TabView(da){
        table.render({
            elem:"#tab_id",
            data:da,
            limit:6,
            toolbar:'#toolbarDemo',
            page:true,
            cols:[[
                {type:'checkbox',align:'center',width:40,},
                {title:'序号',width:60,align:'center',templet:function(data){
                        return data.LAY_INDEX;
                    }},
                {field:'url',title:'课程图片',width:130,align:'center',templet:function(data){
                        if(data.url!=null){
                            return "<img src='"+data.url+"' height='100'>";
                        }else{
                            return "<span>无图片</span>"
                        }

                    }},
                {field:'courseName',title:'课程名称',align:'center'},
                {field:'userName',title:'上传人',align:'center'},
                {field:'courseNprice',title:'价格',align:'center',templet:function(data){
                        return "$"+data.courseNprice+"";
                    }},
                {field:'courseStatus',title:'状态',align:'center',templet:function(data){
                        if(data.courseStatus==2){
                            return  "<input type='checkbox' checked name='courseStatus' value="+data.courseId+" lay-text='上架|下架' lay-skin='switch' lay-filter='switchTest'>"
                        }else{
                            return  "<input type='checkbox' name='courseStatus'  value="+data.courseId+" lay-skin='switch' lay-text='上架|下架' lay-filter='switchTest'>"
                        }
                    }
                },
                {field:'className',title:'分类',align:'center'},
                {field:'saleNum',title:'销量',align:'center'},
                {field:'courseCstatus',title:'审核状态',align:'center',templet:function(data){
                        if(data.courseCstatus==3){
                            return "未审核";
                        }else if(data.courseCstatus==4){
                            return "审核中"
                        }else if(data.courseCstatus==5){
                            return "<p>审核失败</p><a href='#' onclick='javascript:updCstatus(\""+data.courseId+"\")' style='color: #1ABC9C'>重新提交</a></p>";
                        }else{
                            return "<p>审核成功</p><a href='#' onclick='javascript:selectRecord(\""+data.courseId+"\")' style='color: #1ABC9C'>审核详情</a></p>";
                        }
                    }},
                {field:'details',title:"操作",align:'center',templet:function(data){
                        return "<a href='#' onclick='javascript:selectCourseTable(\""+data.courseId+"\",\""+data.type+"\")' style='color: #1ABC9C'>查看</a>&nbsp<a href='#' onclick='javascript:editVue("+data.courseId+","+data.classId+")' style='color: #1ABC9C;margin-left: 10px'>编辑</a></br>" +
                            "<a href='#' onclick='javascript:selLog("+data.courseId+")' style='color: #1ABC9C;'>日志</a>&nbsp<a href='#' onclick='delectCourseTable(\""+data.courseId+"\")' style='color: #1ABC9C;margin-left: 10px'>删除</a>"
                    }}

            ]]
        });
    }
    /*渲染表结束*/

    /*监听状态开关*/
    form.on('switch(switchTest)',function(data){
        //判断状态
        var status=data.elem.checked?2:3;
        updateStatus(data.value,status);

    })

    function updateStatus(id,status){
        $.ajax({
            url:"/SyteacherSelController/updateStatus",
            type:"post",
            dataType:"json",
            data:{"courseId":id,"status":status},
            success:function(data){
                if(data.data>0){
                    layer.msg("状态修改成功",{icon:1},function(index){
                        layer.close();
                        location.reload(true);
                    })
                }else{
                    layer.msg("状态更改失败",{icon:2})
                }
            }
        })
    }

    $("#btn1_id").on("click",function(){
        //获取课程名称
        var title=$("#actId").val();
        //获取课程分类
        var user=$("#city").val();
        //获取课程价格
        var price=$("#accId").val();
        seTab(user,title,price);
    })

})
    //审核详情
    function selectRecord(id){
        layer.open({
            type:2,
            title:"审核结果",
            area:['600px','450px'],
            shade:0.4,
            offset:'auto',
            content:"seRecord.html",
            success:function(layero,index){
                var obj = layero.find('iframe').contents();
                obj.find('input[name=forumId]').val(id);
            }
        })
    }
    //删除课程
    function delectCourseTable(id){
        $.ajax({
            url:"/SyteacherSelController/delectCourseTable",
            type:"post",
            dataType:"json",
            data:{"cid":id},
            success:function(data){
                if(data.data){
                    location.reload(true);
                }
            }
        })
    }
    //课程详情
    function selectCourseTable(id,type){
        var index = layer.open({
            type:2,
            title:"课程详情",
            area:['800px','600px'],
            shade:0.4,
            offset:'auto',
            maxmin: true,
            content:"/operation/comment/TeaCourseView.html",
            success:function(layero,index) {
                //查找当前引入的iframe内容
                var obj = layero.find('iframe').contents();
                //根据选择器选择input,并设置值
                obj.find('input[name=courseId]').val(id);

                obj.find('input[name=type]').val(type);
            }
        });
        layer.full(index);
    }

    //修改课程信息
    function editVue(id,classId){
        layer.open({
            type:2,
            title:"课程详情",
            area:['1200px','600px'],
            shade:0.4,
            offset:'auto',
            content:"EditCourse.html",
            success:function(layero,index){
                var obj = layero.find('iframe').contents();
                obj.find('input[name=course]').val(id);
                obj.find('input[name=courseCatoryId]').val(classId);
            }
        })
    }

    //导入文件
    function couImport(){
        layer.open({
            type:1,
            title:"导入文件",
            area:['250px','200px'],
            shade:0.4,
            offset:'auto',
            content:"<button class='layui-btn' id='btn'>选择文件</button>",
            success:function(layero,index){
                upload.render({
                    elem:"#btn",
                    url:"/SyteacherSelController/addCouImport",
                    done:function (data) {
                        if(data.data.code==0){
                            alert("导入成功");
                            window.parent.location.reload()
                        }
                    },
                    drag:true,
                    accept:'file',
                    multiple:true
                })
            }
        })
    }



//查看日志
function selLog(courseId) {
    location.href = "CourseLog.html?" + courseId;
}

//修改课程状态
function updCstatus(id) {
    var create=localStorage.getItem("user");
    create=JSON.parse(create);//将获取json字符串转json对象

    $.ajax({
        url:"/SyteacherSelController/updCstatus",
        type:"post",
        dataType:"json",
        data:{"cstatus":4,"updateId":create.user_id,"id":id},
        success:function(data){
            if(data.data){
                location.reload(true);
            }
        }
    });
}